package com.tengju.support.application.picture;

import com.tengju.support.application.shared.ApplicationException;
import com.tengju.support.application.shared.ApplicationExceptionCode;
import com.tengju.support.application.shared.PictureUtils;
import com.tengju.support.domain.model.img.LineImg;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Service;

import java.io.File;
import java.time.LocalDate;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

@Slf4j
@Service
public class PictureService {


    /**
     * 获取折线图
     */
    public File generateLineImgStream(LineImg lineImg) {
        try {
            // 生成折线图
            String path = PictureUtils.createLinePort(lineImg.getTitle(),
                    lineImg.getData(), lineImg.getXName(), lineImg.getYName(), lineImg.getImgName());
            return new File(path);
        } catch (Exception e) {
            log.error("生成折线图失败，imgName{}",lineImg.getImgName());
            throw ApplicationException.error(ApplicationExceptionCode.GENERATE_LINE_IMAGE_ERROR);
        }

    }


    @Bean(
            name = {"picClear"}
    )
    public void initFileClear() {
        ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor();
        executorService.scheduleAtFixedRate(
                () -> PictureUtils.clearFile(LocalDate.now().minusDays(1)),
                0, 24*60, TimeUnit.MINUTES);
    }

}
